import axios from 'axios'
import { Toast } from 'antd-mobile'

/* 注册校验 */
export const actionRegister = (userInfo, props) => {
  return dispatch => {
    /* 获取数据库所有用户列表，防止用户重复注册 */
    axios.get('http://localhost:9000/userInfo')
      .then(response => {
      /* flag = {} */
      let flag = response.data.find(item => {
        return item.userName === userInfo.userName || item.password === userInfo.password
      })
        
      if (flag) {
        alert('用户名或账号已存在')
      } else {
        userInfo.password = parseInt(userInfo.password)
        axios.post('http://localhost:9000/userInfo', { ...userInfo })
          .then(res => {
            /* 注册成功跳转到登录页面 */
            props.history.push('/login')
          })
      }
    })
  }
}

/* 登录校验 */
export const actionLogin = (loginInfo, props) => {
  return dispatch => {
    axios.get('http://localhost:9000/userInfo')
    .then(res => {
      let userInfo = res.data.find(item => {
        return item.userName === loginInfo.userName || item.password === loginInfo.password
      })
      
      if (userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))

        let redirect = props.history.location.state && props.history.location.state.from.pathname
        props.history.replace(redirect || '/home')

        return dispatch({
          type: 'mutationLogin',
          value: userInfo
        })
      } else {
        Toast.fail('账号、密码输入错误')
      }
    })
  }
}
